//
//  AppDelegate.swift
//  FMRadio
//
//  Created by 范东 on 2022/7/26.
//

import UIKit
//import CBFlashyTabBarController
import FDNetwork
import FDUIKit

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        if FMRadio.getUserId() > 0 {
            TUILogin.login(Int32(SDKAPPID), userID: String(FMRadio.getUserId()), userSig: FMRadio.getUserSig()) {
                debugPrint("IM登录成功")
                //加入全员大群
                V2TIMManager.sharedInstance().joinGroup(.FullGroupId, msg: "加入全员大群") {
                    debugPrint("加入全员大群成功")
                } fail: { code, msg in
                    debugPrint("加入全员大群失败 code:"+"\(code)"+"msg:"+(msg ?? ""))
                }
            } fail: { code, msg in
                debugPrint("IM登录失败 code:\(code) msg:"+(msg ?? ""))
            }
        }
        setupListener()
        return true
    }
    
    // 配置开发环境证书
    func push_certificateIDForAPNS() -> Int{
        return 34262
    }
    
    func setupListener(){
        TUILogin.add(self)
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        window = FMRadio.getCurrentWindow()
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }
    
    // 统一点击跳转
    // 您可以直接拷贝当前的方法名到您的 AppDelegate 中
    @objc func navigateToTUIChatViewController(_ userID: String, groupID: String){
        // 示例: 点击推送通知后，首先跳转到会话列表页面，然后再会话列表页跳转到聊天页面
          // 1. 获取当前 app 的 tabBarController
          // 2. 获取 tabBarController 的 firstObject，也即 ConversationController
          // 3. 执行 pushToViewController: 跳转到 ChatViewController
          // 跳转到聊天页面后，支持点击左上角的返回按钮回退到主页面
        let tabC = FMRadio.getCurrentWindow().rootViewController
        if !(tabC?.isKind(of: UITabBarController.classForCoder()) ?? false) {
            //正在登录中
            return
        }
        let newTabC = tabC as! UITabBarController
        if newTabC.selectedIndex != 1 {
            newTabC.selectedIndex = 1
        }
        let nav = newTabC.selectedViewController
        let vc = nav?.children.first
        if !(vc?.isKind(of: ConversationController.classForCoder()) ?? false){
            return
        }
        let conv = vc as! ConversationController
        if conv.responds(to: NSSelectorFromString("pushToChatViewController:userID:")) {
            conv.perform(NSSelectorFromString("pushToChatViewController:userID:"), with: groupID, with: userID)
        }
    }
}

extension AppDelegate: TUILoginListener{
    
    func onConnecting() {
        
    }
    
    func onConnectSuccess() {
        
    }
    
    func onConnectFailed(_ code: Int32, err: String!) {
        
    }
    
    func onUserSigExpired() {
        FMRadio.logout()
    }
    
    func onKickedOffline() {
        let alert = UIAlertController(title: NSLocalizedString("Tip", comment: ""), message: NSLocalizedString("Your account logined in another device", comment: ""), preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: NSLocalizedString("reLogin", comment: ""), style: .default, handler: { action in
            let userSign = GenerateTestUserSig.genTestUserSig(String(FMRadio.getUserId()))
            TUILogin.login(Int32(SDKAPPID), userID: String(FMRadio.getUserId()), userSig: userSign) {
                //加入全员大群
                V2TIMManager.sharedInstance().joinGroup(.FullGroupId, msg: "加入全员大群") {
                    debugPrint("加入全员大群成功")
                } fail: { code, msg in
                    debugPrint("加入全员大群失败 code:"+"\(code)"+"msg:"+(msg ?? ""))
                }
            } fail: { code, msg in
                FDMessageView.show(title: NSLocalizedString("Tip", comment: ""), message: msg ?? "", theme: .error)
            }
        }))
        alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: { action in
            FMRadio.logout()
        }))
        window?.rootViewController!.present(alert, animated: true, completion: nil)
    }
    
}

